/* This program outputs a file (or stdin) in a caesar cipher. */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>  //strtol
#include <stdbool.h>
#include <assert.h>
#include <argp.h>

#define DEFAULT_SHIFT 1

char fileName [128];
short int shift = DEFAULT_SHIFT;

const char * argp_program_version = "0.1";
const char * argp_program_bug_address = "jbranso@dismail.com";

error_t argp_err_exit_status;

static const struct argp_option options [] =
  {
   {"file" , 'f', "FILE", 0, "Output the caesar cipher of a file." },
   {"shift", 's', "INT", 0,  "Specify the shift of the cipher." },
   { 0 }
  };

//define an argp parse function
error_t argp_parser (int opt, char *arg, struct argp_state *state)
{
  extern char fileName [];
  extern short int shift;
  switch (opt)
    {
      // if this parser function is called on an option that it doesn't recognize, then don't do anything.
    default:
      return ARGP_ERR_UNKNOWN;
    case 'f':
      {
        memcpy (fileName, arg, strlen (arg));
        break;
      }
    case 's':
      {
        shift = abs ((int) strtol (arg, NULL, 0));
        if (shift >= 26)
          shift = shift % 26;
        break;
      }
    }
  return 0;
}

/* a string containing the basic usage of this program. */
struct argp argp =
  {
   options, argp_parser, 0,
   "A simple program implementing a caesar cipher.\nThe default shift is 1."
  };

/* This function decrypts letters.
   print_shift('a', 1) -> 'b'
   print_shift('B', 1) -> 'C'
*/
void print_shifted (int shift, int c)
{
  unsigned int lower, upper; // upper is 'a' or 'A', and lower is 'z' or 'Z'
  if (isupper (c))
    {
      lower = 'A'; 
      upper = 'Z'; 
    }
  else
    {
      lower = 'a'; 
      upper = 'z'; 
    }
  // if we add the shift, and the resulting char is not a letter, then
  // we need to do tweak things.
  c += shift; 
  if ( abs (c) > upper)
    c = lower + (c - (upper + 1)); 
  putchar (c);  
}

void encrypt (int shift, FILE * stream)
{
  int c;  /* If I make this a char c, then 'z' + 7 = -128 */
  while ((c = getc(stream)) != EOF)
    {
      //if the char is a number or punctionation, etc, print it.
      if (!(isalpha ((int) c)))
        putchar(c);
      else
        print_shifted(shift, c);
    }
}

int main (int argc, char **argv) {
  extern char fileName [];
  extern short int shift;
  argp_parse (&argp, argc, argv, 0, 0, 0);
  FILE * stream;
  if ((stream = fopen (fileName, "r")) == NULL)
    stream = stdin;
  encrypt (shift, stream);
  fclose (stream);
  return 0;
}
